package com.hang.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.common.BizErrorCodeEnum;
import com.hang.common.BizException;
import com.hang.config.RedisConfig;
import com.hang.mapper.ClazzMapper;
import com.hang.mapper.StudentMapper;
import com.hang.model.Clazz;
import com.hang.model.ClazzStudent;
import com.hang.model.Student;
import com.hang.service.ClazzStudentService;
import com.hang.mapper.ClazzStudentMapper;
import com.hang.util.listener.ClazzStudentListener;
import com.hang.vo.ClazzStudentVo;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 *
 */
@Service
@Slf4j
public class ClazzStudentServiceImpl extends ServiceImpl<ClazzStudentMapper, ClazzStudent>
    implements ClazzStudentService{

    @Autowired
    private RedisConfig redisConfig;

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;
    /**
     * 导入班级——学生信息
     * @param clazzID
     * @param multipartFile
     *
     * 将班级-学生信息先存储进redis中，作为列表存储
     * 将班级id作为key,学号作为value,以list形式存储
     *
     * 以后先去redis中取，后续将数据同步到mysql中
     */
    @Override
    public void importData(String clazzID, MultipartFile multipartFile) {
        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplate();
        try {
            EasyExcel.read(multipartFile.getInputStream(), ClazzStudentVo.class,new ClazzStudentListener(baseMapper,clazzID,redisTemplate))
                    .sheet()
                    .doRead();
        }catch (IOException e){
            log.error("导入信息失败:{}",e.toString());
        }
    }

    @Override
    public void updateClazzCount(String clazzId) {
        if(StringUtils.isBlank(clazzId)){
            throw new BizException(BizErrorCodeEnum.CLAZZ_FOUND_FAIL);
        }

        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplate();

        List list = redisTemplate.opsForList().range(clazzId, 0, -1);
        List<String> students;
        if(list.size() == 0){
            //这个班级还没有存入相对应的数据，先存入
            students = new ArrayList<>();
        }else {
            students= (List<String>) list.get(0);
        }

        //临时学生列表
        List<String> studentList = new ArrayList<>();

        int count = 0;      //班级实际人数
        if(ObjectUtils.isEmpty(students) || students.size() == 0){
            //说明在redis中没有此记录,去mysql中取
            QueryWrapper<ClazzStudent> wrapper = new QueryWrapper<>();
            wrapper.eq("clazz_id",clazzId);

            List<ClazzStudent> clazzStudents = baseMapper.selectList(wrapper);
            if(ObjectUtils.isEmpty(clazzStudents) || clazzStudents.size() == 0){
                //班级没有学生
                throw new BizException(BizErrorCodeEnum.STUDENT_IS_EMPTY);
            }

            //否则则读出学生列表中的相关信息，并且将学号写入到redis中
            for (ClazzStudent clazzStudent : clazzStudents){
                QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
                studentQueryWrapper.eq("student_id",clazzStudent.getStudentId());

                Student student = studentMapper.selectOne(studentQueryWrapper);

                studentList.add(clazzStudent.getStudentId());
                if(!ObjectUtils.isEmpty(student)){
                    count++;
                }
            }

            redisTemplate.opsForList().rightPush(clazzId,studentList);
        }else {
            //直接从缓存中取
            for(String stu_id : students){
                QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
                studentQueryWrapper.eq("student_id",stu_id);

                Student stu = studentMapper.selectOne(studentQueryWrapper);
                if(!ObjectUtils.isEmpty(stu)){
                    count++;
                }
            }
        }

        //更新班级人数
        QueryWrapper<Clazz> clazzQueryWrapper = new QueryWrapper<>();
        clazzQueryWrapper.eq("clazz_id",clazzId);

        Clazz clazz = clazzMapper.selectOne(clazzQueryWrapper);
        clazz.setCounts(count);

        clazzMapper.updateById(clazz);
    }
}




